package com.masterclient.app.modules.aftersale;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.masterclient.app.BaseActivity;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.base.ProgressLoginDialog;
import com.eoner.baselib.utils.notify.RxBus;
import com.masterclient.app.businessmodule.minemodule.address.ChangeAddressActivity;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.eoner.baselibrary.bean.aftersale.ReturnGoodsBean;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsContract;
import com.masterclient.app.modules.aftersale.contract.ReturnGoodsPresenter;
import com.eoner.uikit.dialog.simple.ChooseHeadImgDialog;
import com.eoner.baselibrary.bean.personal.UploadImgBean;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.masterclient.app.widget.TitlebarView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import top.zibin.luban.Luban;

import static com.masterclient.app.modules.aftersale.AfterSaleDetailActivity.NEW_AFTERSALE;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.IMAGE_PICKER;
import static com.masterclient.app.businessmodule.usermodule.userinfo.UserInfoActivity.REQUEST_CODE_SELECT;

@Route(path = AroutePath.RETURN_REDELIVER_ACTIVITY)
public class ReturnRedeliverActivity extends BaseActivity<ReturnGoodsPresenter> implements ReturnGoodsContract.View {

    @BindView(R.id.title_view)
    TitlebarView titleView;
    @BindView(R.id.return_redeliver_goodsimg)
    ImageView returnRedeliverGoodsimg;
    @BindView(R.id.return_redeliver_goodsname)
    TextView returnRedeliverGoodsname;
    @BindView(R.id.return_redeliver_goodsattr)
    TextView returnRedeliverGoodsattr;
    @BindView(R.id.return_redeliver_reasonicon)
    ImageView returnRedeliverReasonicon;
    @BindView(R.id.return_redeliver_reason)
    TextView returnRedeliverReason;
    @BindView(R.id.return_redeliver_reasonrl)
    RelativeLayout returnRedeliverReasonrl;
    @BindView(R.id.edit_num_reduce)
    TextView returnRedeliverNumreduce;
    @BindView(R.id.edit_num)
    TextView returnRedeliverNum;
    @BindView(R.id.edit_num_plus)
    TextView returnRedeliverNumplus;
    @BindView(R.id.return_redeliver_numtotal)
    TextView returnRedeliverNumtotal;
    @BindView(R.id.return_redeliver_addressno)
    TextView returnRedeliverAddressno;
    @BindView(R.id.return_redeliver_addressarrow)
    ImageView returnRedeliverAddressarrow;
    @BindView(R.id.return_redeliver_addressdefault)
    TextView returnRedeliverAddressdefault;
    @BindView(R.id.return_redeliver_addressuser)
    TextView returnRedeliverAddressuser;
    @BindView(R.id.return_redeliver_addressphone)
    TextView returnRedeliverAddressphone;
    @BindView(R.id.return_redeliver_addressdetails)
    TextView returnRedeliverAddressdetails;
    @BindView(R.id.return_redeliver_addressll)
    LinearLayout returnRedeliverAddressll;
    @BindView(R.id.return_redeliver_addresslayout)
    RelativeLayout returnRedeliverAddresslayout;
    @BindView(R.id.return_redeliver_remark)
    TextView returnRedeliverRemark;
    @BindView(R.id.return_redeliver_desc)
    EditText returnRedeliverDesc;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.rl_add_img)
    RelativeLayout rlAddImg;
    @BindView(R.id.gridLayout)
    GridLayout gridLayout;
    @BindView(R.id.return_redeliver_submit)
    TextView returnRedeliverSubmit;

    @Autowired(name = "product_id")
    String product_id;
    @Autowired(name = "update")
    String update;
    @Autowired(name = "order_id")
    String order_id;

    private ReturnGoodsBean.DataBean dataBean;
    private List<UploadImgBean.DataBean> images ;
    private List<File> imageFileList;
    private String addressId, reseanId, refund_reason_id, refund_type_id;
    private int maxGoodsNum;
    private int IMAGE_SIZE = 9;
    private ReturnReasonDialog returnReasonDialog;
    private ChooseHeadImgDialog headImgDialog;
    private ImagePicker imagePicker;
    private RxPermissions rxPermissions;
    private ProgressLoginDialog progressDialog;
    private int imageHeight;
    private List<ReturnGoodsBean.DataBean.ShReasonBean> reason ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_return_redeliver);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);


        imageHeight = ((int) ((ScreenUtils.getScreenWidth()-ScreenUtils.dp2px(23))/4f))-ScreenUtils.dp2px(9);
        Utils.setDin(returnRedeliverNum,this);
        maxGoodsNum = 1;
        images =  new ArrayList<>();
        reason = new ArrayList<>();
        progressDialog = new ProgressLoginDialog(this);
        titleView.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

        mPresenter.preAfterSale("reissue_apply_base", product_id, update, order_id);


        rxPermissions = new RxPermissions(this);

        headImgDialog = new ChooseHeadImgDialog(mContext, "上传图片", "相册", "拍照");
        headImgDialog.setOnChooseListener(new ChooseHeadImgDialog.OnChooseListener() {
            @Override
            public void album() {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
            }

            @Override
            public void photo() {
                rxPermissions
                        .requestEach(Manifest.permission.CAMERA)
                        .subscribe(permission -> { // will emit 2 Permission objects
                            if (permission.granted) {
                                // `permission.name` is granted !
                                Intent intent = new Intent(mContext, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                            } else if (permission.shouldShowRequestPermissionRationale) {
                                // Denied permission without ask never again
                            } else {
                                // Denied permission with ask never again
                                // Need to go to the settings
                            }
                        });
            }
        });

        imagePicker = ImagePicker.getInstance();
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(IMAGE_SIZE);
    }


    @Override
    public void preAfterSaleInfo(ReturnGoodsBean.DataBean dataBean) {
        this.dataBean = dataBean;
        if (dataBean.getSh_product() != null ) {
            if (!TextUtils.isEmpty(dataBean.getSh_product().getSh_qty_ordered())) {
                maxGoodsNum = Integer.parseInt(dataBean.getSh_product().getSh_qty_ordered());
                returnRedeliverNumtotal.setText("件(最多"+ maxGoodsNum +"件)");
                setNum(1);
            }
            ViewTransformUtil.glideImageView(this, dataBean.getSh_product().getSh_image(), returnRedeliverGoodsimg, new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0), R.mipmap.defaults);
            returnRedeliverGoodsname.setText(dataBean.getSh_product().getSh_name());
            returnRedeliverGoodsattr.setText(dataBean.getSh_product().getSh_attribute_text());
        }

        if (dataBean.getSh_address() != null && !TextUtils.isEmpty(dataBean.getSh_address().getSh_id())){
            addressId = dataBean.getSh_address().getSh_id();
            returnRedeliverAddressll.setVisibility(View.VISIBLE);
            returnRedeliverAddressno.setVisibility(View.GONE);
            returnRedeliverAddressphone.setText(dataBean.getSh_address().getSh_mobile());
            returnRedeliverAddressuser.setText("收货人："+dataBean.getSh_address().getSh_full_name());
            returnRedeliverAddressdetails.setText(dataBean.getSh_address().getSh_address());
        }


        if (dataBean.getSh_refund_remark() != null && dataBean.getSh_refund_remark().length() > 0)
            returnRedeliverRemark.setText("注：" + dataBean.getSh_refund_remark());

        if (dataBean.getSh_refund_info() != null && !TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_id())) {
            //设置原因
            for (ReturnGoodsBean.DataBean.ShReasonBean reason : dataBean.getSh_new_reason().getSh_replacement().getSh_is_received()) {
                if (reason.getSh_relation_id().equals(dataBean.getSh_refund_info().getSh_relation_id())) {
                    returnRedeliverReason.setText(reason.getSh_reason_name());
                    reseanId = reason.getSh_relation_id();
                    refund_reason_id = reason.getSh_refund_reason_id();
                    refund_type_id = reason.getSh_refund_type_id();
                    break;
                }

            }

            returnRedeliverDesc.setText(dataBean.getSh_refund_info().getSh_description());

            returnRedeliverNum.setText(dataBean.getSh_refund_info().getSh_qty_refunded());
            setNum(TextUtils.isEmpty(dataBean.getSh_refund_info().getSh_qty_refunded())?0:Integer.parseInt(dataBean.getSh_refund_info().getSh_qty_refunded()));

            if (dataBean.getSh_refund_info().getSh_images() != null && dataBean.getSh_refund_info().getSh_images().size() > 0) {
                int i = 1;
                for (ReturnGoodsBean.DataBean.ShRefundInfoBean.ShImagesBean imagesBean : dataBean.getSh_refund_info().getSh_images()) {
                    UploadImgBean.DataBean dataBean1 = new UploadImgBean.DataBean();
                    dataBean1.setSh_image_url(imagesBean.getSh_url());
                    dataBean1.setSh_name(imagesBean.getSh_url());
                    images.add(dataBean1);

                    if (IMAGE_SIZE > images.size()) {
                        rlAddImg.setVisibility(View.VISIBLE);
                    }else {
                        rlAddImg.setVisibility(View.GONE);
                    }
                    View imageItem = View.inflate(mContext, R.layout.item_img, null);
                    ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.getLayoutParams().height = imageHeight;
                    imageView.getLayoutParams().width = imageHeight;
                    ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                    iv_delete.setTag(dataBean1.getSh_image_url());
                    iv_delete.setOnClickListener(v -> {
//                        if (IMAGE_SIZE > images.size()) {
                            rlAddImg.setVisibility(View.VISIBLE);
//                        }
                        gridLayout.removeView(imageItem);
                        removeImage((String) iv_delete.getTag());
                    });
                    ViewTransformUtil.glideImageView(ReturnRedeliverActivity.this,dataBean1.getSh_image_url(),imageView,new Transformation[]{
                            new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);

                    gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                    i++;
                }
            }
        }



    }

    @Override
    public void applyAfterSaleSuccess() {
        progressDialog.dismiss();
        RxBus.$().post(Config.AFTERSALE_REFRESH);
        setResult(ChooseAfterSaleActivity.RESULT_SUCCESS);
        startActivitry(AfterSaleDetailActivity.class, new String[][]{{"product_id", product_id}, {"order_id", order_id}, {"type", NEW_AFTERSALE}});
        finish();
    }

    @Override
    public void onUploadSuccess(UploadImgBean.DataBean dataBean) {
        if (images == null) {
            images = new ArrayList<>();
        }
        images.add(dataBean);
        if (IMAGE_SIZE <= images.size()) {
            rlAddImg.setVisibility(View.GONE);
        }
    }

    @Override
    public void showError(String msg) {
        progressDialog.dismiss();
        showToast(msg);
    }

    @Override
    public void showError(String code, String msg) {
        progressDialog.dismiss();
        showToast(msg);
    }

    @OnClick({R.id.rl_add_img, R.id.return_redeliver_reasonrl, R.id.edit_num_reduce, R.id.edit_num_plus, R.id.return_redeliver_addresslayout, R.id.return_redeliver_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_add_img:
                if (images == null) {
                    imagePicker.setSelectLimit(IMAGE_SIZE);
                } else {
                    imagePicker.setSelectLimit(IMAGE_SIZE - images.size());
                }
                headImgDialog.show();
                break;
            case R.id.return_redeliver_reasonrl:
                if (dataBean != null) {
                    reason = dataBean.getSh_new_reason().getSh_replacement().getSh_is_received();
                }
                if (reason == null || reason.size()<=0) return;
                if (returnReasonDialog == null) {
                    returnReasonDialog = new ReturnReasonDialog(mContext);
                    returnReasonDialog.setOnConfirmListener(new ReturnReasonDialog.OnConfirmListener() {
                        @Override
                        public void onConfirm(int index) {
                            reseanId = reason.get(index).getSh_relation_id();
                            refund_reason_id = reason.get(index).getSh_refund_reason_id();
                            refund_type_id = reason.get(index).getSh_refund_type_id();
                            returnRedeliverReason.setText(reason.get(index).getSh_reason_name());
                        }
                    });
                }
                returnReasonDialog.show();
                returnReasonDialog.setList(reason);
                break;
            case R.id.edit_num_reduce:
                setNum(Integer.parseInt(returnRedeliverNum.getText().toString())-1);
                break;
            case R.id.edit_num_plus:
                setNum(Integer.parseInt(returnRedeliverNum.getText().toString())+1);
                break;
            case R.id.return_redeliver_addresslayout:
                startActivitryForResult(ChangeAddressActivity.class, null);
                break;
            case R.id.return_redeliver_submit:
                if (dataBean == null) return;
                if (TextUtils.isEmpty(reseanId)) {
                    showToast("补发原因不能为空");
                    return;
                }
                if (TextUtils.isEmpty(addressId)) {
                    showToast("收货信息不能为空，请重新编辑");
                    return;
                }

                List<String> imageStrs = new ArrayList<>();

                progressDialog.show();
                progressDialog.setDesc("加载中...");
                if (images != null) {
                    for (UploadImgBean.DataBean dataBean : images) {
                        imageStrs.add(dataBean.getSh_image_url());
                    }
                }
                mPresenter.applyAfterSale("", "", "", "", returnRedeliverDesc.getText().toString().trim(),
                        imageStrs, product_id, returnRedeliverNum.getText().toString(), reseanId, "2", "", update, order_id,
                        "",addressId,"reissue_apply_put",null,refund_reason_id,refund_type_id,"");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode){
            case 103:
                AddressBean.DataBean.ShItemsBean itemsBean = (AddressBean.DataBean.ShItemsBean) data.getSerializableExtra("default_address");
                addressId = itemsBean.getSh_id();
                returnRedeliverAddressll.setVisibility(View.VISIBLE);
                returnRedeliverAddressno.setVisibility(View.GONE);
                returnRedeliverAddressdefault.setVisibility("1".equals(itemsBean.getSh_is_default())?View.VISIBLE:View.GONE);
                returnRedeliverAddressphone.setText(itemsBean.getSh_mobile());
                returnRedeliverAddressuser.setText("收货人："+itemsBean.getSh_full_name());
                returnRedeliverAddressdetails.setText(itemsBean.getSh_province() + itemsBean.getSh_city() + itemsBean.getSh_area() + itemsBean.getSh_address());
                break;

            case ImagePicker.RESULT_CODE_ITEMS:
                if (data != null && requestCode == IMAGE_PICKER) {//相册
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    uploadImages(images);
                } else if (data != null && requestCode == REQUEST_CODE_SELECT) {//拍照
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    uploadImages(images);
                }
                break;
        }
    }


    private void uploadImages(ArrayList<ImageItem> images) {
        List<File> files = new ArrayList<>();
        for (ImageItem item : images) {
            File imgFile = new File(item.path);
            files.add(imgFile);
        }
//                mPresenter.uploadImage(files,"customer");
        if (files.size() > 0) {
            if (imageFileList == null) {
                imageFileList = new ArrayList<>();
            }
            //压缩并更新视图,上传图片
            Observable.fromIterable(files).map(new Function<File, File>() {
                @Override
                public File apply(@NonNull File file) throws Exception {
                    if (file != null) {
                        return Luban.with(mContext).load(file).get();
                    }
                    return null;
                }
            }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<File>() {
                @Override
                public void accept(@NonNull File file) throws Exception {
                    if (file != null) {
                        imageFileList.add(file);

                        if (IMAGE_SIZE <= imageFileList.size()) {
                            rlAddImg.setVisibility(View.GONE);
                        }else {
                            rlAddImg.setVisibility(View.VISIBLE);
                        }
                        View imageItem = View.inflate(mContext, R.layout.item_img, null);
                        ImageView imageView = (ImageView) imageItem.findViewById(R.id.image);
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        imageView.getLayoutParams().height = imageHeight;
                        imageView.getLayoutParams().width = imageHeight;
                        ImageView iv_delete = (ImageView) imageItem.findViewById(R.id.iv_delete);
                        iv_delete.setTag(file.getName() + ".jpeg");
                        iv_delete.setOnClickListener(v -> {
                            gridLayout.removeView(imageItem);
                            imageFileList.remove(file);
//                            if (IMAGE_SIZE > imageFileList.size()) {
                                rlAddImg.setVisibility(View.VISIBLE);
//                            }
                            removeImage((String) iv_delete.getTag());
                        });

                        gridLayout.addView(imageItem, gridLayout.getChildCount() - 1);
                        ViewTransformUtil.glideImageView(ReturnRedeliverActivity.this,file.toURI().toURL().toString(),imageView,new Transformation[]{
                                new CenterCrop(), new RoundedCornersTransformation(ScreenUtils.dp2px(4), 0)}, R.mipmap.defaults);

//                        Glide.with(ReturnGoodsActivity.this).load(file)
//                                .apply(new RequestOptions().placeholder(R.mipmap.defaults).error(R.mipmap.defaults)).into(imageView);
//                        App.picasso.load(file).fit().into(imageView);
                        mPresenter.uploadImage(file, "review ", file.getName() + ".jpeg");
                    }
                }
            });
        }
    }

    public void setNum(int currentNum){
        if (currentNum>=1&&currentNum<=maxGoodsNum){
            returnRedeliverNum.setText(currentNum+"");
        }
        returnRedeliverNumplus.setEnabled(currentNum<maxGoodsNum);
        returnRedeliverNumreduce.setEnabled(currentNum>1);
    }


    private void removeImage(String name) {
        int p = -1;
        for (int i = 0; i < images.size(); i++) {
            if (name.equals(images.get(i).getSh_name())) {
                p = i;
                break;
            }
        }

        if (p > -1) {
            images.remove(p);
        }
    }
}
